import React, {useCallback, useEffect, useState} from "react";
import {ApplyTeamModel} from "@/common/apis/model";

import {relationDeleteApi, teamApplyListApi, teamPassApi} from "@/common/apis/home_datasource";
import Utils from "@/utils/common";

import {View} from "@tarojs/components";
import {Button, Cell, Empty} from "@antmjs/vantui";
import AssetImage from "@/common/AssetImage";
import StyleUtils from "@/utils/style_utils";


definePageConfig({
  navigationBarTitleText: '课题组申请列表',
})

export default function ApplyTeamPage() {
  const [items, setItems] = useState<ApplyTeamModel[]>()

  const fetchData = useCallback(() => {
    teamApplyListApi().then((res2) => {
      if (res2) {
        setItems(res2)
      }

    })
  }, [setItems]);

  useEffect(() => {
    setItems(undefined);
    fetchData()
    return () => {
    }
  }, [fetchData]);


  return (
    <View>
      <View style={{minHeight: "100vh", padding: "10px 0", boxSizing: 'border-box', backgroundColor: AssetImage.bg}}>
        {
          items && !Utils.isEmpty(items) ? <View>
            {
              items.map((item, index) => {
                return <RecordItem3 key={index} item={item} OnGetDat={fetchData}/>
              })
            }
          </View> : <Empty description='暂无数据'/>
        }
      </View>
    </View>
  )
}


function RecordItem3(props) {
  const item = props.item as ApplyTeamModel


  //0是申请 1是通过
  const handlerButton = useCallback((isAgree) => {
    const api = !isAgree ? relationDeleteApi(item.teamId, item.id) : teamPassApi(item.id);
    api.then((res2) => {
      if (res2) {
        Utils.showToast(isAgree ? '已同意' : '已拒绝')
        if (props.OnGetDat) {
          props.OnGetDat()
        }
      }
    })
  }, []);
  const renderButtons = useCallback(() => {
    return (
      <View>
        <Button style={{marginLeft: '10px'}} size='small' type='info' hairline plain onClick={(e) => {
          handlerButton(true)
        }}
        >
          同意
        </Button>
        <Button style={{marginLeft: '10px'}} size='small' type='danger' hairline plain onClick={(e) => {
          handlerButton(false)
        }}
        >
          拒绝
        </Button>
      </View>
    )
  }, []);

  return (
    <View style={{...StyleUtils.getMiniCellStyle()}}>
      <Cell title={`${item.username}申请加入${item.teamName}`}>
        {
          renderButtons()
        }
      </Cell>
    </View>
  )
}
